<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>工单管理</title>
	</head>
	<body>
		<div class="layui-container">
			<div class="layui-form" lay-filter="order-form">
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">创建人</label>
						<div class="layui-input-inline">
							<input type="text" name="creator" id="creator" placeholder="请输入创建人" autocomplete="off" class="layui-input">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">处理人</label>
						<div class="layui-input-inline">
							<input type="text" name="handler" id="handler" placeholder="请输入处理人" autocomplete="off" class="layui-input">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">工单号</label>
						<div class="layui-input-inline">
							<input type="text" name="searchOrderNo" id="searchOrderNo" placeholder="请输入工单编号" autocomplete="off" class="layui-input">
						</div>
					</div>
					<!--<div class="layui-inline">
					<label class="layui-form-label">所属办事处</label>
					<div class="layui-input-inline">
						<input type="text" name="area" placeholder="请输入办事处"
							autocomplete="off" class="layui-input">
					</div>
				</div>-->

				</div>
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label" id="status" style="width:80px">工单状态</label>
						<div class="layui-input-inline">
							<select name="status">
								<option value="-1">请选择</option>
								<option value="0">审批中</option>
								<option value="1">待处理</option>
								<option value="2">处理中</option>
								<option value="3">驳回</option>
								<option value="4">结束</option>
								<option value="5">关闭</option>
							</select>
						</div>
					</div>

					<div class="layui-inline">
						<label class="layui-form-label">范围</label>
						<div class="layui-input-inline" style="width: 140px;">
							<input type="text" class="layui-input" id="startDate" name="startDate">
						</div>
						<div class="layui-form-mid">-</div>
						<div class="layui-input-inline" style="width: 140px;">
							<input type="text" class="layui-input" id="endDate" name="endDate">
						</div>
					</div>
					<div class="layui-inline">
						<button class="layui-btn layuiadmin-btn-list" lay-submit="" lay-filter="order-search">
							<i class="layui-icon layui-icon-search"></i>
						</button>
					</div>
					<div class="layui-inline">
						<button class="layui-btn layuiadmin-btn-list export">导出EXCEL</button>
					</div>

				</div>
			</div>
		</div>
		<table class="layui-hide" id="ordersTable" lay-filter="ordersTable"></table>
		<script type="text/javascript">
			var table = layui.table;
			var form = layui.form;
			form.render();

			window._gettingCustomerLocation = false;
			// 高德地图地理编码
			function gaodeMapGeo(address) {
				var ak = "83d2a8f1731ffd9706874206a8b5989f";
				var apiUrl = "https://restapi.amap.com/v3/geocode/geo?output=json&key=" + ak + "&address=" + address;
				$.ajax({
					url: apiUrl,
					async: false,
					success: function(result) {
						_gettingCustomerLocation = false;
						if (result.status == "1" && result.geocodes.length > 0) {
							window._gettingCustomerLocation = true;
							//var location = result.geocodes[0].location;
							//_customerLocation = location;
						} else {
							layer.msg("获取客户地理坐标失败, 请填写正确的客户地址!");
						}
					},
					error: function(err) {
						window._gettingCustomerLocation = false;
						layer.msg("获取客户地理坐标失败, 请填写正确的客户地址!");
						console.log(err);
					}
				})
			}
			
			function getUserRoleAndDetail(callback) {
				var orderId = $('#applyForm2').find('input[name="orderId"]').val();
				$.ajax({
					url: window.basePath + '/order/checkIsApprovaled',
					method: 'post',
					headers: {"token" : window.token},
					dataType: 'json',
					data: {
						orderId: orderId
					},
					success: function(data) {
						console.log(data);
						callback(data);
					},
					error: function(data) {
						layer.close(_index);
						layer.msg('网络异常！');
					}
				});
			}

			function checkDate(startTime, endTime) {
				if (startTime.length > 0 && endTime.length > 0) {
					var startTmp = startTime.split("-");
					var endTmp = endTime.split("-");
					var sd = new Date(startTmp[0], startTmp[1], startTmp[2]);
					var ed = new Date(endTmp[0], endTmp[1], endTmp[2]);
					if (sd.getTime() > ed.getTime()) {
						return false;
					}
				}
				return true;
			}

			var creator = '';
			var handler = '';
			var area = '';
			var status = -1;
			var startDate = '';
			var endDate = '';

			form.on('submit(order-search)', function(data) {

				creator = data.field.creator;
				handler = data.field.handler;
				area = data.field.area;
				status = data.field.status;
				startDate = data.field.startDate;
				endDate = data.field.endDate;
				searchOrderNo = data.field.searchOrderNo;

// 				if (startDate == '' || startDate == null) {
// 					layer.msg('开始时间不能为空!');
// 					return false;
// 				}
// 
// 				if (startDate) {
// 					if (endDate == '' || endDate == null) {
// 						layer.msg('结束时间不能为空！');
// 						return false;
// 					}
// 				}

				if (startDate && endDate) {
					if (!checkDate(startDate, endDate)) {
						layer.msg('开始时间不能大于结束时间！');
					}
				}


				orderTableNs.reload({
					where: {
						creator: creator,
						handler: handler,
						area: area,
						status: status,
						startDate: startDate,
						endDate: endDate,
						searchOrderNo: searchOrderNo
					},
					page: {
						curr: 1
					}
				});
				return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
			});
			var empCode = window.empCode;
			var orderTableNs = table.render({
				elem: '#ordersTable',
				height: 'full-220',
				url: window.basePath + '/order/findAllOrdersByWeb?empCode=' + empCode,
				method: "post",
				headers: {"token" : window.token},
				cols: [
					[{
						type: 'checkbox'
					}, {
						fixed: 'left',
						field: 'status',
						title: '工单状态',
						minWidth: 80,
						templet: '#statusTpl'
					}, {
						fixed: 'left',
						field: 'orderNo',
						width: 180,
						title: '工单编号'
					}, {
						fixed: 'left',
						field: 'orderFrom',
						width: 120,
						title: '工单类型'
					}, {
						field: 'orderFromName',
						width: 180,
						title: '标题'
					}, {
						field: 'creator',
						minWidth: 100,
						title: '工单创建人'
					}, {
						field: 'creatorNo',
						minWidth: 100,
						title: '创建人工号'
					}, {
						field: 'handle',
						minWidth: 100,
						title: '工单处理人'
					}, {
						field: 'handleNo',
						minWidth: 100,
						title: '处理人工号'
					}, {
						field: 'customerName',
						minWidth: 180,
						title: '客户名称'
					}, {
						field: 'createTime',
						title: '工单创建时间',
						minWidth: 200
					}, {
						field: 'startTime',
						title: '工单开始时间',
						minWidth: 200
					}, {
						field: 'endTime',
						title: '工单结束时间',
						minWidth: 200
					}, {
						fixed: 'right',
						width: 260,
						align: 'center',
						toolbar: '#barDemo'
					}]
				],
				text: {
					none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
				},
				page: true
			});

			//是否为经理
			var isManage = 1;

			function checkMannge() {
				var empCode = window.empCode;
				$.ajax({
					url: window.basePath + '/sys/checkIsManager',
					data: {
						workNo: empCode
					},
					headers: {"token" : window.token},
					method: "post",
					success: function(data) {
						if (data.message == '操作成功') {
							isManage = 0;
						}
					},
					error: function() {}
				})
			}
			checkMannge();

			//监听表格复选框选择
			var $ = layui.jquery;

			table.on('tool(ordersTable)', function(obj) {
				var data = obj.data; //获得当前行数据
				var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
				var tr = obj.tr; //获得当前行 tr 的DOM对象
				if (layEvent === 'del') {
					layer.confirm('您确定要删除该工单数据吗？', function(index) {
						var _index = layer.load(3);
						//向服务端发送删除指令
						$.ajax({
							url: window.basePath + '/order/deleteOrder',
							headers: {"token" : window.token},
							method: "post",
							data: {
								orderId: data.id
							},
							success: function(data) {
								layer.close(_index);
								if (data.success) {
									obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
								}
								layer.msg(data.message);
							},
							error: function() {
								layer.close(_index);
								layer.msg('网络异常！');
							}
						});
					});
				}

				if (layEvent === 'apply') {
					var url = "";
					if (isManage == 0) {
						url = window.basePath + '/admin/views/orders/apply.html';
						showDialog({
							title: '工单审批',
							template: url,
							showbtns: false,
							width: 650,
							height: 600,
							success: function() {
								$('#applyForm2').find('input[name="orderId"]').val(data.id);
								if (data.hasOwnProperty("handleNo")) {
									$('#currentHandler').html(data.handle + '(' + data.handleNo + ')');
									$('#thisHandler').val(data.handleNo);
								}
								if (data.hasOwnProperty("contactName")) {
									$('#contactName').val(data.contactName);
								}
								if (data.hasOwnProperty("customerPhone")) {
									$('#customerPhone').val(data.customerPhone);
								}
								if (data.hasOwnProperty("customerAddress")) {
									$('#customerAddress').val(data.customerAddress);
									gaodeMapGeo(data.customerAddress);
								}
								
								if (data.hasOwnProperty("managerNo")) {
									$('#applyForm2').find('input[name="managerNo"]').val(data.managerNo);
								}
								if (window.empCode.toUpperCase() != data.managerNo.toUpperCase()) {
									$("#selectEm").hide();
									$("#applyForm2ContactName").hide();
									$("#applyForm2CustomerPhone").hide();
									$("#applyForm2CustomerAddress").hide();
								}

								$('#customerAddress').on('blur', function() {
									gaodeMapGeo($('#customerAddress').val());
								});
							}
						});
					} else {
						url = window.basePath + '/admin/views/orders/applyNormal.html';
						showDialog({
							title: '工单审批',
							template: url,
							showbtns: false,
							width: 650,
							height: 360,
							success: function() {
								$('#applyForm').find('input[name="orderId"]').val(data.id);
								if (data.hasOwnProperty("handleNo")) {
									$('#currentHandler').html(data.handle + '(' + data.handleNo + ')');
								}
							}
						});
					}
				}
				if (layEvent === 'detail') {
					showDialog({
						title: '工单查看',
						template: window.basePath + '/admin/views/orders/orderDetail.html',
						showbtns: false,
						width: 650,
						height: 600,
						success: function() {
							$.ajax({
								url: window.basePath + '/mobile/order/findOrderDetailAndLogsByOrderId?orderId=' + data.id,
								headers: {"token" : window.token},
								method: "post",
								success: function(result) {
									//								    console.log(result);
									$('.layui-form-item.onlineProblems').hide();
									$('.layui-form-item.projectDelivery').hide();

									var order = result.obj;
									// $('#orderNo').text(order.orderNo);
									$('#orderFrom').text(order.orderFrom);
									$("#customerName").text(order.customerName);
									$("#onlineProblemsName").text(order.onlineProblemsName);
									$("#projectName").text(order.orderFromName);
									$("#customAddress").text(order.customerAddress);
									$("#contactName").text(order.contactName);
									$('#customerPhone').text(order.customerPhone);
									$('#taskDesc').text(order.taskDesc);
									$('#planTime').text(order.planTime);
									$('#handle').text(order.handle);
									$('#orderNo').text(order.orderNo);
									$('#order-handler').text(order.handle + " (" + order.handleNo + ")");
									$('#order-creator').text(order.creator + " (" + order.creatorNo + ")");
									$('#createTime').text(order.createTime);
									if (order.warns) {
										$('#warnning').text(order.warns[0].warnContent);
									} else {
										$('#warnning').text('无');
									}
									if (order.medias) {
										for(var i = 0; i < order.medias.length; i ++) {
											// var imgSrc = "https://iworktest.uniview.com/api/v1/medias/images/" + order.medias[i].mediaId;
											var imgSrc = "https://iwork.uniview.com/api/v1/medias/images/" + order.medias[i].mediaId;
											var lightBox = "<a href='" + imgSrc + "' data-lightbox='livephoto' data-title='live photo-" + (i + 1) + "'><img src='" + imgSrc + "'/></a>";
											$("#livePhotos").append(lightBox);
										}
									} else {
										$('#livePhotosDiv').hide();
									}
									var isUrgent = order.isUrgent;
									if (isUrgent == 0) {
										$('#isUrgent').text("是");
									} else {
										$('#isUrgent').text("否");
									}
									var order_form = order.orderFrom.split(",");
									for (var i = 0; i < order_form.length; i++) {
										if (order_form[i] == '网上问题') {
											$('.layui-form-item.onlineProblems').show();
										}
										if (order_form[i] == '项目交付' || order_form[i] == '对外测试' || order_form[i] == '备件维修') {
											$('.layui-form-item.projectDelivery').show();
										}
									}
									var logs = result.list;
									if (logs.length > 0) {
										var html = '';
										var remark = '';
										var handler = '';
										var assignName = '';
										var creator = '';
										for (var i = 0; i < logs.length; i++) {
											remark = '';
											handler = '';
											assignName = '';
											creator = '';
											if (logs[i].hasOwnProperty("reMark")) {
												remark = '<p>备注:&nbsp;&nbsp;' + logs[i].reMark + '</p>';
											}
											if (logs[i].hasOwnProperty("handler")) {
												handler = '<p>处理内容:&nbsp;&nbsp;' + logs[i].handler + '</p>';
											}
											if (logs[i].hasOwnProperty("assignName")) {
												assignName = '<p>流转到:&nbsp;&nbsp;' + logs[i].assignName + '</p>';
											}
											if (logs[i].hasOwnProperty("creator")) {
												creator = logs[i].creator + '&nbsp;&nbsp;&nbsp;';
											}
											html += '<li class="layui-timeline-item">' +
												'    <i class="layui-icon layui-timeline-axis">&#xe63f;</i>' +
												'    <div class="layui-timeline-content layui-text">' +
												'      <h3 class="layui-timeline-title">' + creator + logs[i].createTime.substring(0, 16) + '</h3>' +
												handler + assignName + remark +
												'    </div>' +
												'  </li>';
										}
										$("#detailForm").after(
											'<blockquote class="layui-elem-quote" style="margin-top: 20px;">工单处理流程</blockquote>' +
											'<ul class="layui-timeline">' + html + '</ul>');
									}
								}
							})
						}
					});
				}

				if (layEvent === 'urge') {
					layer.confirm('您确定要发送催办通知吗？', function(index) {
						var _index = layer.load(3);
						//向服务端发送催办通知指令
						$.ajax({
							url: window.basePath + '/order/urgeOrder',
							headers: {"token" : window.token},
							method: "post",
							data: {
								orderId: data.id
							},
							success: function(data) {
								layer.close(_index);
								layer.msg(data.message);
							},
							error: function() {
								layer.close(_index);
								layer.msg('网络异常！');
							}
						});
					});
				}

				if (layEvent === 'copy' || layEvent === 'child' || layEvent === 'update') {
					var url = 'orders/addOrders.html?id=' + data.id + '&type=';
					if (layEvent === 'copy') {
						url += "copy";
					} else if (layEvent === "child") {
						url += "child";
					} else {
						url += "update";
					}
					$(this).attr("data-url", url);
				}

			});

			//导出数据
			$('.export').on('click', function() {
				var creator = $("#creator").val();
				var handler = $("#handler").val();
				var status = $("#status").val();
				var startDate = $("#startDate").val();
				var endDate = $("#endDate").val();
				if (startDate == '' || endDate == '') {
					layer.msg('请选择导出时间范围！');
					return;
				}
				if (!checkDate(startDate, endDate)) {
					layer.msg('开始时间不能大于结束时间！');
					return;
				}
				layer.load(3);
				$.ajax({
					url: window.basePath + '/orderReport/exportOrderHandleReport',
					dataType: 'json',
					headers: {"token" : window.token},
					method: "post",
					data: {
						empCode: empCode,
						creator: creator,
						handler: handler,
						status: status,
						startDate: startDate,
						endDate: endDate
					},
					success: function(data) {
						layer.closeAll("loading");
						if (data.success === true) {
							window.open(data.obj);
						}
						layer.msg(data.message);
					},
					error: function() {
						layer.closeAll("loading");
					}
				});
			});

			//工单审核回调函数
			$(document).on('applyRefresh', function() {
				//刷新表格
				orderTableNs.reload({
					where: {
						creator: creator,
						handler: handler,
						area: area,
						status: status,
						startDate: startDate,
						endDate: endDate
					}
				});
			});

			var laydate = layui.laydate;

			//执行一个laydate实例
			laydate.render({
				elem: '#startDate' //指定元素
			});
			laydate.render({
				elem: '#endDate' //指定元素
			});
		</script>
		<script type="text/html" id="barDemo">

	{{#  if((d.status === '0'  && window.empCode && d.handleNo && window.empCode.toUpperCase() === d.handleNo.toUpperCase())
	|| (d.status === '3' && window.empCode.toUpperCase() != d.creatorNo.toUpperCase())){ }}
   <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="apply">审核</a>
  {{#  } }}

  {{#  if((d.status === '0' || d.status === '1') && window.empCode.toUpperCase() != d.handleNo.toUpperCase()){ }}
   <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="urge">催办</a>
  {{#  } }}

  <a href="javascript:;" data-url="" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="copy">复制</a>
  {{#  if(d.status === '1' || d.status === '2' || d.status === '4' ){ }}
  <a href="javascript:;" data-url="" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="child">衍生</a>
  {{#  } }}
  {{#  if((d.status === '3' && window.empCode 
		&& d.handleNo && window.empCode.toUpperCase() === d.creatorNo.toUpperCase()
		&& d.creatorNo.toUpperCase() === d.handleNo.toUpperCase()) || (d.managerNo.toUpperCase() === window.empCode.toUpperCase())){ }}
		<a href="javascript:;" data-url="" class="layui-btn layui-btn-warm layui-btn-xs" lay-event="update">修改</a>
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
  {{#  } }}
  <a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>
</script>

<script type="text/html" id="statusTpl">
	{{#  if(d.status === '0'){ }}
    <span style="color: #1E9FFF;">审核中</span>
  {{#  } else if(d.status === '1') { }}
    <span style="color: #009688;">待处理</span>
	{{#  } else if(d.status === '2') { }}
    <span style="color: #F581B1;">处理中</span>
	{{#  } else if(d.status === '3') { }}
    <span style="color: #FF5722;">驳回</span>
	{{#  } else if(d.status === '4') { }}
    <span style="color: #5FB878;">已结束</span>
	{{#  } else if(d.status === '5') { }}
    <span style="color: #2F4056;">已关闭</span>
	{{#  } else if(d.status === '6') { }}
    <span style="color: #01AAED;">草稿</span>
  {{#  } }}
</script>
	</body>
</html>
